-- SkyExploreShopM
-- Create by chendh
-- 天空之城特殊商店系统

module("SkyExploreShopM", package.seeall);

-- 商品配置信息
local exploreShopConfig = {}

-- 模块初始化
function init()
    -- 转换下audio信息表
    local explore_shop_CSV = get_explore_shop_CSV();
    for i = 1, #explore_shop_CSV do
        exploreShopConfig[explore_shop_CSV[i].id] = parseGoods(explore_shop_CSV[i]);
    end

    explore_shop_CSV = {};
end

-- 检索触发事件信息
function query(id, path)
    local m = exploreShopConfig[id]

    if not m or path == "" or not path then
        return m
    end

    return m[path]
end

-- 解析商品数据
function parseGoods(info)
    -- 商品
    local arr = string.explode(string.sub(info.goods, 3, -2), ",");
    if string.startWith(info.goods, "1(") then
        info.goods = { 1, tonumber(arr[1]), tonumber(arr[2]), };
    elseif string.startWith(info.goods, "6(") then
        info.goods = { 6, tonumber(arr[1]), tonumber(arr[2]), };
    else
        info.goods = { 8, tonumber(arr[1]), tonumber(arr[2]), };
    end

    -- 价格
    local price = {}
    arr = string.explode(string.sub(info.price, 3, -2), ",");
    if string.startWith(info.price, "1(") then
        -- 物品
        price = { 1, tonumber(arr[1]), tonumber(arr[2]), }
    elseif string.startWith(info.price, "2(") then
        -- 属性
        price = { 2, arr[1], tonumber(arr[2]), }
    end

    info.price = price;

    return info;
end

-- 购买结果
function notifyBuyGoodsResult(exploreIndex, index, result)
    local skyExplore = ME.user.dbase:query("sky_explore", {});
    local info = skyExplore[exploreIndex];

    if not info then
        return;
    end

    local sold = info["sold"] or {};
    table.insert(sold, index);
    info["sold"] = sold;

    EventMgr.fire(event.SKY_EXPLORE_SHOP_BUY, { ["result"] = result, ["exploreIndex"] = exploreIndex, ["index"] = index });
end

-- 判断能否购买物品，只判断价格
function canBuyGoods(exploreIndex, goodsIndex)
    local skyExplore = ME.user.dbase:query("sky_explore", {});
    local info = skyExplore[exploreIndex];
    local goodsId = info["goods"][goodsIndex];
    local goodsInfo = query(goodsId);

    -- 没有该商店信息
    if not info or not goodsInfo then
        return "no_goods";
    end

    -- 如果已经买过了
    if table.indexOf(info["sold"] or {}, goodsIndex) >= 1 then
        return "sold_out"   -- 商品已售完
    end

    local price = goodsInfo.price;
    local ok = true;
    if price[1] == 1 then
        -- 物品
        ok = ItemM.getAmount(ME.user, price[2]) >= price[3]
        if not ok then
            return string.format("item_%d_lack", price[2]);  -- 物品数量不足
        end
    elseif price[1] == 2 then
        -- 属性
        ok = ME.user.dbase:query(price[2], 0) >= price[3]
        if not ok then
            return price[2] .. "_lack"  -- 属性数量不足
        end
    else
        return false
    end

    return ok
end

-- 购买
function buyGoods(exploreIndex, index)
    -- 直接发送消息给服务器
    Operation.cmd_buy_explore_shop_goods(exploreIndex, index);
end